package com.version1_3.dao.implement;

import com.SQLGroup.SQLAccess;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.util.property.Properties;
import com.version1_1.dao.PageDao;
import com.version1_3.dao.PageDao1_3;
import com.version1_3.model.MainPageModel;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by reeves on 2015/12/23.
 */
@Repository
public class PageDaoImpl13 implements PageDao1_3 {
    private static final Logger LOGGER = Logger.getLogger(PageDaoImpl13.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PageDao pageDao; // 复用version1.1 Dao层的一些方法


    // 1. 登陆用户获取主界面信息
    @Override
    public MainPageModel getMainPage(int firstType, int userId, int pageNumber) {
        // 能力规划版块
        // 用户关注信息：[[2.学科],[3.能力],[4.规划],[5.兴趣]]
        String userFocusStr = getUserFocusStr(userId);
        JSONArray jsonArray = JSON.parseArray(userFocusStr);
        MainPageModel mainPageModel = new MainPageModel();

        if (firstType < 2 || firstType > 5) {
            LOGGER.error("请求的一级分类ID不符合规范,firstType: " + firstType);
            return null;
        }

        JSONArray firstFocusJsonArray = jsonArray.getJSONArray(firstType - 2);


        // 获取文章列表信息
        int begin = Properties.Size_MainPageThird * (pageNumber - 1);
        int end = Properties.Size_MainPageThird * (pageNumber);

        if (firstFocusJsonArray.size() <= Properties.Size_MainPageThird * (pageNumber)) {
            end = firstFocusJsonArray.size();
        }

        List pageList = new ArrayList<>();
        for (int i = begin; i < end; i++) {
            List tempList = getThirdInfoNoLogin(firstFocusJsonArray.getIntValue(i), Properties.PageSize_MainPagePerThrid);
            pageList.addAll(tempList);
        }

        if (pageList == null || pageList.isEmpty()) {
            mainPageModel.setLast(true);
        }

        mainPageModel.setPageList(pageList);

        // 如果是第一页,则获取滑图信息
        if (pageNumber == 1) {
            mainPageModel.setTitleList(getTitleList(firstType));
        }

        return mainPageModel;
    }

    // 2. 未登陆用户获取主界面信息
    @Override
    public MainPageModel getMainPageNoLogin(JSONArray firstFocusJsonArray, int firstType, int pageNumber) {
        MainPageModel mainPageModel = new MainPageModel();

        // 获取文章列表信息
        int begin = Properties.Size_MainPageThird * (pageNumber - 1);
        int end = Properties.Size_MainPageThird * (pageNumber);

        if (firstFocusJsonArray.size() <= Properties.Size_MainPageThird * (pageNumber)) {
            end = firstFocusJsonArray.size();
        }

        List pageList = new ArrayList<>();
        for (int i = begin; i < end; i++) {
            List tempList = getThirdInfoNoLogin(firstFocusJsonArray.getIntValue(i), Properties.PageSize_MainPagePerThrid);
            pageList.addAll(tempList);
        }

        mainPageModel.setPageList(pageList);

        if (pageList == null || pageList.isEmpty()) {
            mainPageModel.setLast(true);
        }

        // 如果是第一页,则获取滑图信息
        if (pageNumber == 1) {
            mainPageModel.setTitleList(getTitleList(firstType));
        }

        return mainPageModel;
    }

    // 3. 获取三级分类界面信息
    @Override
    public List getThirdPageList(int thirdTypeId, int pageNumber) {

        @SuppressWarnings("deprecation")
        int count = jdbcTemplate.queryForInt(SQLAccess.SelectAThirdTypeInfoCountVersion1_3, new Object[]{thirdTypeId});
        if ((pageNumber - 1) * Properties.PageSize_ThirdPage >= count) {
            LOGGER.info("获取三级分类页面预览信息数据,用户请求分页数过大...");
            return null;
        }

        return jdbcTemplate.queryForList(SQLAccess.SelectAThirdTypePageInfoVersion1_3, new Object[]{
                thirdTypeId, (pageNumber - 1) * Properties.PageSize_ThirdPage,
                Properties.PageSize_ThirdPage});
    }

    // 4. 根据三级分类 ID 获取三级分类描述文字
    @Override
    public String getThridTypeDescription(int thirdTypeId) {
        return jdbcTemplate.queryForObject(SQLAccess.SelectThirdTypeDescriptionVersion1_3, new Object[]{thirdTypeId}, java.lang.String.class);
    }

    /*
    * 工具类方法
    */

    /**
     * 获取一定条数的三级分类信息
     */
    public List getThirdInfoNoLogin(int typeId, int pageSize) {
        return jdbcTemplate.queryForList(SQLAccess.SelectThridTypePageInfoVersion1_3, new Object[]{typeId, pageSize});
    }

    /**
     * 获取一级分类滑图信息
     */
    @Cacheable(value = {"pageTitleVersion1_3"})
    public List getTitleList(int firstType) {
        //大图信息数组
        List titleList = null;
        try {
            titleList = jdbcTemplate.queryForList(SQLAccess.SelectFirstTypeSlideInfoVersion1_2, new Object[]{firstType, Properties.TitlePic_Num});
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.error("获取主界面大图信息数组,未查询到大图信息,EmptyResultDataAccessException...", exception);
        }
        return titleList;
    }

    /**
     * 获取用户关注分类字符串
     */
    public String getUserFocusStr(int userId) {
        return jdbcTemplate.queryForObject(SQLAccess.SelectUserFocusInfoVersion1_3, new Object[]{userId}, java.lang.String.class);
    }

    /**
     * @Description: 获取除正文之外其他信息
     */
    @Override
    public Map<String, Object> getPageOtherInfo(int userId, int pageId) {
        String sql = "";

        Map<String, Object> pageOtherInfoMap = new HashMap<>();

        /**
         * 根据pageId取出praNum,criNum,typeId,并根据typeId判断用户是否订阅了此分类
         */
        boolean isSubscri = false;

        sql = "SELECT praNum,criNum,typeId FROM page_info WHERE pageId=?";
        //LOGGER.error("获取正文的其他信息,pageId: " + pageId);
        Map<String, Object> queryMap1 = jdbcTemplate.queryForMap(sql, new Object[]{pageId});

        sql = "SELECT thirdTypeId,typeBgImgSrc FROM type_info WHERE id=?";
        Map<String, Object> queryMap0 = jdbcTemplate.queryForMap(sql, new Object[]{(int) queryMap1.get("typeId")});

        sql = "SELECT userFocusTypeIds FROM user_info WHERE userId=?";

        String userFocusId = "";
        try {
            userFocusId = jdbcTemplate.queryForObject(sql, new Object[]{userId}, String.class);
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.info("未登陆用户请求除html页面外的其他信息...");
        }

        // 兼容version1_2和version1_3接口
        if (userFocusId.contains(String.valueOf(queryMap0.get("thirdTypeId")))) {
            isSubscri = true;
        }

        //--------------------到了添加数据的时候-----------------//
        pageOtherInfoMap.put("praNum", (int) queryMap1.get("praNum"));
        pageOtherInfoMap.put("criNum", (int) queryMap1.get("criNum"));
        pageOtherInfoMap.put("typeBgImgSrc", (String) queryMap0.get("typeBgImgSrc"));
        pageOtherInfoMap.put("adPicUrl", Properties.Page_adPicUrl);
        pageOtherInfoMap.put("adLink", "null");
        pageOtherInfoMap.put("isSubscri", isSubscri);

        /**
         * 从info_comment得到用户是否对该篇文章点击好文或者水文
         */
        int userChoice = -1;
        sql = "SELECT id,choice FROM info_comment WHERE userId=? AND pageId=?";
        try {
            // 防止info_comment有多个userId=-1而pageId相同的记录造成查询出错
            int userIdTemp = 0;
            if (userId != -1) {
                userIdTemp = userId;
            }

            Map<String, Object> queryMap2 = jdbcTemplate.queryForMap(sql, new Object[]{userIdTemp, pageId});
            userChoice = (int) queryMap2.get("choice");
        } catch (EmptyResultDataAccessException ex) {
            LOGGER.info("从info_comment中无法找到用户: " + userId + " 对pageId为：" + pageId + " 的文章的评价");
        }

        //--------------------到了添加数据的时候-----------------//
        pageOtherInfoMap.put("userChoice", userChoice);

        /**
         * 获取推荐文章列表,文章是随机的
         */
        List<Map<String, Object>> recomList = new ArrayList<>();

        try {
            recomList = jdbcTemplate.queryForList(SQLAccess.SelectRecommendPageVersion1_2, new Object[]{(int) queryMap1.get("typeId")});
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.error("获取推荐文章出错，没有找到数据");
        }

        //--------------------到了添加数据的时候-----------------//
        pageOtherInfoMap.put("recomArtc", recomList);

        /**
         * 获取评论列表
         */
        List<Map<String, Object>> commentList = jdbcTemplate.queryForList(SQLAccess.SelectFirstPageComment, new Object[]{pageId, Properties.PageSize_PageComment});


        for (int i = 0; i < commentList.size(); i++) {
            commentList.get(i).put("hasPraised", pageDao.checkPraised((int) commentList.get(i).get("commentId"), userId));
        }

        //--------------------到了添加数据的时候-----------------//
        pageOtherInfoMap.put("comFirPage", commentList);


        /**
         * 获取评论总条数
         */
        int commentNum = jdbcTemplate.queryForObject(SQLAccess.SelectPageCommentCount, new Object[]{pageId}, Integer.class);

        //--------------------到了添加数据的时候-----------------//
        pageOtherInfoMap.put("comNum", commentNum);

        return pageOtherInfoMap;
    }

    /**
     * 获取文章的
     *
     * @param pageId
     * @return
     */
    @Override
    public Map<String, Object> getArticleDetail(int pageId) {
        String sql = "SELECT recomPos,thirdTypeName,editorId,pageType FROM page_info,type_info WHERE page_info.typeId=type_info.thirdTypeId AND pageId=?";

        return jdbcTemplate.queryForMap(sql, new Object[]{pageId});
    }

    /**
     * 获取推送信息
     *
     * @param key
     * @return
     */
    @Override
    public List<Map<String, Object>> getPushArticleInfo(String key) {
        String sql = "SELECT pageId,secondType,firstTitle,imageSrc FROM tuisong WHERE firstTitle like '%" + key + "%'";
        return jdbcTemplate.queryForList(sql);
    }
}
